'use strict';

exports.main = async (event, context) => {
	const { startDate, endDate } = event;
	
	try {
		const db = uniCloud.database();
		const _ = db.command;
		
		console.log('开始获取报表数据，时间范围:', startDate, '至', endDate);
		
		// 并行获取所有数据
		const [usersData, tasksData, tradesData, violationsData] = await Promise.all([
			getUsersReport(db, _, startDate, endDate),
			getTasksReport(db, _, startDate, endDate),
			getTradesReport(db, _, startDate, endDate),
			getViolationsReport(db, _, startDate, endDate)
		]);
		
		console.log('数据获取完成:', {
			users: usersData.length,
			tasks: tasksData.length,
			trades: tradesData.length,
			violations: violationsData.length
		});
		
		// 计算统计数据
		const stats = {
			totalUsers: usersData.length,
			totalTasks: tasksData.length,
			totalTradeAmount: tradesData.reduce((sum, item) => sum + parseFloat(item.amount || 0), 0).toFixed(2),
			totalViolations: violationsData.length
		};
		
		return {
			code: 200,
			message: 'success',
			data: {
				stats,
				users: usersData,
				tasks: tasksData,
				trades: tradesData,
				violations: violationsData
			}
		};
	} catch (error) {
		console.error('获取报表数据失败:', error);
		return {
			code: 500,
			message: '服务器错误',
			error: error.message
		};
	}
};

// 获取用户报表数据
async function getUsersReport(db, _, startDate, endDate) {
	try {
		const userCollection = db.collection('uni-id-users');
		
		// 不使用时间范围限制，查询所有用户
		let condition = {};
		
		console.log('查询用户（所有时间）');
		
		// 获取用户数据 - 限制返回50条（减少数量以提高性能）
		const result = await userCollection.where(condition)
			.field({
				_id: true,
				username: true,
				nickname: true,
				register_date: true,
				last_login_date: true,
				status: true
			})
			.orderBy('register_date', 'desc') // 按注册时间倒序
			.limit(50)
			.get();
		
		const users = result.data || [];
		console.log('获取到用户数:', users.length);
		
		// 批量查询所有用户的任务数和交易额
		const userIds = users.map(u => u._id);
		
		// 批量查询任务数
		const taskCountsPromise = db.collection('taskList')
			.where({
				publisher_id: _.in(userIds)
			})
			.field({
				publisher_id: true
			})
			.get();
		
		// 批量查询交易额
		const tradesPromise = db.collection('payment_records')
			.where({
				user_id: _.in(userIds),
				status: 'success' // 只统计成功的交易
			})
			.field({
				user_id: true,
				amount: true
			})
			.get();
		
		// 并行查询
		const [taskCountsResult, tradesResult] = await Promise.all([
			taskCountsPromise,
			tradesPromise
		]);
		
		// 统计每个用户的任务数
		const taskCountMap = {};
		(taskCountsResult.data || []).forEach(task => {
			const uid = task.publisher_id;
			taskCountMap[uid] = (taskCountMap[uid] || 0) + 1;
		});
		
		// 统计每个用户的交易额
		const tradeAmountMap = {};
		(tradesResult.data || []).forEach(trade => {
			const uid = trade.user_id;
			tradeAmountMap[uid] = (tradeAmountMap[uid] || 0) + parseFloat(trade.amount || 0);
		});
		
		console.log('任务统计完成，用户数:', Object.keys(taskCountMap).length);
		console.log('交易统计完成，用户数:', Object.keys(tradeAmountMap).length);
		
		// 组装用户数据
		const usersWithStats = users.map((user) => {
			return {
				userId: user._id ? user._id.substring(0, 8).toUpperCase() : 'N/A',
				username: user.username || '-',
				nickname: user.nickname || user.username || '未设置',
				registerDate: user.register_date || new Date(),
				lastLogin: user.last_login_date || user.register_date || new Date(),
				taskCount: taskCountMap[user._id] || 0,
				tradeAmount: (tradeAmountMap[user._id] || 0).toFixed(2),
				status: user.status === 0 ? 'active' : user.status === 1 ? 'banned' : 'inactive',
				statusText: user.status === 0 ? '正常' : user.status === 1 ? '已封禁' : '未激活'
			};
		});
		
		return usersWithStats;
	} catch (error) {
		console.error('获取用户报表失败:', error);
		return [];
	}
}

// 获取任务报表数据
async function getTasksReport(db, _, startDate, endDate) {
	try {
		const taskCollection = db.collection('taskList');
		
		// 不使用时间范围限制，查询所有任务
		let condition = {};
		
		console.log('查询任务（所有时间）');
		
		// 获取任务数据 - 限制返回100条
		const result = await taskCollection.where(condition)
			.field({
				_id: true,
				title: true,
				publisher_id: true,
				publisher_name: true,
				type: true,
				reward: true,
				publish_time: true,
				complete_time: true,
				status: true
			})
			.orderBy('publish_time', 'desc') // 按发布时间倒序
			.limit(100)
			.get();
		
		const tasks = result.data || [];
		console.log('获取到任务数:', tasks.length);
		
		// 简化处理：不查询发布者详细信息
		const formattedTasks = tasks.map(task => {
			let statusText = '未知';
			let status = 'pending';
			
			if (task.status === 'pending' || task.status === 'processing') {
				statusText = '进行中';
				status = 'pending';
			} else if (task.status === 'completed') {
				statusText = '已完成';
				status = 'completed';
			} else if (task.status === 'cancelled') {
				statusText = '已取消';
				status = 'cancelled';
			}
			
			return {
				taskId: task._id ? task._id.substring(0, 8).toUpperCase() : 'N/A',
				title: task.title || '无标题',
				publisher: task.publisher_name || (task.publisher_id ? task.publisher_id.substring(0, 6) : '未知'),
				category: task.type || '其他',
				amount: parseFloat(task.reward || 0).toFixed(2),
				publishTime: task.publish_time || new Date(),
				completeTime: task.complete_time || null,
				status,
				statusText
			};
		});
		
		return formattedTasks;
	} catch (error) {
		console.error('获取任务报表失败:', error);
		return [];
	}
}

// 获取交易报表数据
async function getTradesReport(db, _, startDate, endDate) {
	try {
		const paymentCollection = db.collection('payment_records');
		
		// 不使用时间范围限制，查询所有交易
		let condition = {};
		
		console.log('查询交易（所有时间）');
		
		// 获取交易数据 - 限制返回100条
		const result = await paymentCollection.where(condition)
			.field({
				_id: true,
				payment_id: true,
				user_id: true,
				amount: true,
				create_time: true,
				status: true,
				payment_method: true,
				type: true
			})
			.orderBy('create_time', 'desc') // 按创建时间倒序
			.limit(100)
			.get();
		
		const trades = result.data || [];
		console.log('获取到交易数:', trades.length);
		
		// 简化处理：不查询用户详细信息
		const formattedTrades = trades.map(trade => {
			let statusText = '未知';
			let status = 'pending';
			
			if (trade.status === 'success') {
				statusText = '成功';
				status = 'success';
			} else if (trade.status === 'pending') {
				statusText = '处理中';
				status = 'pending';
			} else if (trade.status === 'failed') {
				statusText = '失败';
				status = 'failed';
			} else if (trade.status === 'cancelled') {
				statusText = '已取消';
				status = 'cancelled';
			}
			
			// 支付方式映射
			const paymentMethodMap = {
				'wallet': '余额支付',
				'wechat': '微信支付',
				'alipay': '支付宝'
			};
			
			return {
				tradeId: trade._id ? trade._id.substring(0, 8).toUpperCase() : 'N/A',
				orderNo: trade.payment_id || '-',
				buyer: trade.user_id ? trade.user_id.substring(0, 6) : '未知',
				seller: '平台',
				amount: parseFloat(trade.amount || 0).toFixed(2),
				tradeTime: trade.create_time || new Date(),
				paymentMethod: paymentMethodMap[trade.payment_method] || '其他',
				status,
				statusText
			};
		});
		
		return formattedTrades;
	} catch (error) {
		console.error('获取交易报表失败:', error);
		return [];
	}
}

// 获取违规记录报表数据
// 注意：违规信息存储在uni-id-users表的violation_count字段中，不是独立表
async function getViolationsReport(db, _, startDate, endDate) {
	try {
		const userCollection = db.collection('uni-id-users');
		
		// 查询有违规记录的用户（不限制时间）
		const condition = {
			violation_count: _.gte(1) // 至少有1次违规
		};
		
		console.log('查询违规用户（所有时间）');
		
		// 获取违规用户数据 - 限制返回100条
		const result = await userCollection.where(condition)
			.field({
				_id: true,
				username: true,
				nickname: true,
				violation_count: true,
				violation_records: true,
				register_date: true
			})
			.orderBy('violation_count', 'desc')
			.limit(100)
			.get();
		
		const users = result.data || [];
		console.log('获取到违规用户数:', users.length);
		
		// 展开违规记录
		const formattedViolations = [];
		users.forEach(user => {
			const violationRecords = user.violation_records || [];
			
			// 如果有详细的违规记录，展开显示
			if (violationRecords.length > 0) {
				violationRecords.forEach((record, index) => {
					formattedViolations.push({
						recordId: `${user._id.substring(0, 6)}-${index + 1}`,
						username: user.nickname || user.username || '未知用户',
						violationType: record.type || '未分类',
						content: record.reason || '违规内容',
						punishment: record.punishment || '警告',
						punishTime: record.time || user.register_date || new Date(),
						auditor: '系统',
						severity: record.severity || 'low',
						severityText: record.severity === 'high' ? '严重' : record.severity === 'medium' ? '中等' : '轻微'
					});
				});
			} else {
				// 没有详细记录，只显示违规次数
				formattedViolations.push({
					recordId: user._id.substring(0, 8).toUpperCase(),
					username: user.nickname || user.username || '未知用户',
					violationType: '多次违规',
					content: `累计违规${user.violation_count}次`,
					punishment: '警告',
					punishTime: user.register_date || new Date(),
					auditor: '系统',
					severity: user.violation_count >= 5 ? 'high' : user.violation_count >= 3 ? 'medium' : 'low',
					severityText: user.violation_count >= 5 ? '严重' : user.violation_count >= 3 ? '中等' : '轻微'
				});
			}
		});
		
		return formattedViolations.slice(0, 100); // 限制返回100条
	} catch (error) {
		console.error('获取违规报表失败:', error);
		return [];
	}
}

